package com.idanchuang.component.businesslog.es.index;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * The StatusPolicy
 *
 * @since 2020/7/17
 */
public class StatusPolicy implements ToXContentObject {

    static final ParseField NAME_FIELD = new ParseField("name");
    static final ParseField ACTIONS = new ParseField("actions");
    static final ParseField TRANSITIONS = new ParseField("transitions");

    private String name;
    private List<ActionsPolicy> actions;
    private List<TransitionsPolicy> transitions;

    public StatusPolicy(String name, List<ActionsPolicy> actions, List<TransitionsPolicy> transitions) {
        this.name = name;
        this.actions = actions;
        this.transitions = transitions;
    }

    public String getName() {
        return name;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        builder.field(NAME_FIELD.getPreferredName(), name);
        builder.startArray(ACTIONS.getPreferredName());
        for (ActionsPolicy action : actions) {
            action.toXContent(builder, params);
        }
        builder.endArray();
        builder.startArray(TRANSITIONS.getPreferredName());
        for (TransitionsPolicy transition : transitions) {
            transition.toXContent(builder, params);
        }
        builder.endArray();
        builder.endObject();
        return builder;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, actions, transitions);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        StatusPolicy other = (StatusPolicy) obj;
        return Objects.equals(name, other.name) &&
                Objects.equals(actions, other.actions) &&
                Objects.equals(transitions, other.transitions);
    }

    @Override
    public String toString() {
        return Strings.toString(this);
    }
}
